package org.example.ratelimit2.impl;

import org.example.ratelimit2.MyRateLimiter;

public class CounterRateLimiter implements MyRateLimiter {

    /**
     * 每秒被限制请求数
     */
    private final long permitsPerSecond;

    /**
     * 上一次窗口开始时间
     */
    private long timestamp = System.currentTimeMillis();

    private int counter;

    public CounterRateLimiter(long permitsPerSecond) {
        this.permitsPerSecond = permitsPerSecond;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis();
        // 窗口内请求数量小于阈值，更新计数放行，否则拒绝请求
        if (now - timestamp < 1000) {
            if (counter < permitsPerSecond) {
                counter++;
                return true;
            } else {
                return false;
            }
        }
        // 时间窗口过期，重新计数和开窗
        counter = 0;
        timestamp = System.currentTimeMillis();
        return true;
    }
}
